import {isAliPay} from "./is.ts"

export function Ready(callback: any) {
    if (isAliPay()) {
        // 如果 jsbridge 已经注入则直接调用
        // @ts-ignore
        if (window.AlipayJSBridge) {
            callback && callback()
        } else {
            // 如果没有注入则监听注入的事件
            // @ts-ignore
            document.addEventListener('AlipayJSBridgeReady', callback, false)
        }
    }
}

export function jsApiCall(apiName: string, params: any = {}, callback?: (data: any) => void) {
    Ready(() => {
        AlipayJSBridge.call(apiName, params, callback)
    })
}

const generateOptions = (url: string) => {
    console.log(url)
    return {
        showProgress: 'NO',
        showTitleBar: 'NO',
        transparentTitle: 'always',
    }
}

/**
 * 打开一个链接页
 * @param url /view/main/index.html
 * @param param 参数对象
 */
export function pushWindow(url: string, param: any = {}) {
    if (import.meta.env.MODE == 'locality') {

        window.location.href = !url.startsWith('http') ? location.origin + url : url

        // AlipayJSBridge.call('pushWindow', {
        //   url: !url.startsWith('http') ? location.origin + url : url,
        //   param,
        //   passData: param,
        // })
    } else {

        AlipayJSBridge.call('pushWindow', {
            url,
            param: {
                ...generateOptions(url),
                ...param,
            },
            passData: {
                ...generateOptions(url),

                ...param,
            },
        })
    }
}

/**
 * 关闭当前页
 */
export function popWindow(backData: any = {}) {
    if (isAliPay()) {
        AlipayJSBridge.call('popWindow', {
            data: backData,
        })
    }
}

/**
 * 打开其他应用
 * @param appId
 * @param params {
 *    url:/view/main/index.html
 * }
 * @param callback
 */
export function startApp(
    appId: string,
    params: {
        url?: string
        [key: string]: any
    } = {
        appClearTop: false,
        startMultApp: 'YES',
    },
    callback: any = (res: any) => {
        console.log(res)
    },
) {
    if (import.meta.env.MODE == 'locality') {
        // alert(params.url)
        // alert(location.origin + params.url)
        AlipayJSBridge.call(
            'startApp',
            {
                appId,
                param: {
                    ...params,
                    url: !params.url?.startsWith('http') ? location.origin + params.url : params.url,
                    ...generateOptions(params.url || ''),
                },
            },
            function (result) {
                callback && callback(result)
            },
        )
    } else {
        AlipayJSBridge.call(
            'startApp',
            {
                appId,
                param: {
                    ...params,
                    ...generateOptions(params.url || ''),
                },
            },
            function (result) {
                callback && callback(result)
            },
        )
    }
}

/**
 * 退出当前应用
 */
export function exitApp() {
    AlipayJSBridge.call('exitApp')
}

/**
 * 发送通知
 * @param key
 * @param params
 */
export function postNotification(key: string, params: object) {
    Ready(() => {
        AlipayJSBridge.call(
            'postNotification',
            {
                name: key,
                data: params,
            },
            function () {},
        )
    })
}

/**
 * 接收通知
 * @param key
 * @param cb
 */

export function addNotifyListenerH5(key: string, cb: any) {
    Ready(() => {
        removeNotifyListenerH5(key)
        AlipayJSBridge.call(
            'addNotifyListener',
            {
                name: `NEBULANOTIFY_${key}`,
            },
            cb,
        )
    })
}

export function removeNotifyListenerH5(key: string) {
    Ready(() => {
        AlipayJSBridge.call('removeNotifyListener', {
            name: `NEBULANOTIFY_${key}`,
        })
    })
}

export function getAPDataStoragePromise(key: any) {
    if (!isAliPay()) {
        return Promise.resolve({
            data: {},
        })
    }
    return new Promise((resolve) => {
        Ready(() => {
            AlipayJSBridge.call(
                'getAPDataStorage',
                {
                    type: 'common',
                    business: 'HBC_DATA',
                    key,
                },
                function (result) {
                    if (result?.success) {
                        resolve(result)
                    } else {
                        resolve({
                            data: null,
                        })
                    }
                },
            )
        })
    })
}
